%% Simulate the finite-sample distribution of the PIT statistics

function S_stat_sim = simulate_S_stat_distribution(N, finite_dist_sim)
% INPUT: number of validation studies N, size of the simulated sample from the
% finite-sample distribution of S statistics finite_dist_sim
% OUTPUT: simulated S statistics S_stat_sim 

    % Initialization
    S_stat_sim = zeros(finite_dist_sim, 1);
    edges = [0, 0.2, 0.4, 0.6, 0.8, 1];
    expected_count = 0.2 * N; 

    % Simulate N_sim datasets from U[0,1] and compute S statistics
    for sim = 1:finite_dist_sim
        % Generate N random numbers from U[0,1]
        simulated_PIT = rand(N, 1);

        % Compute histogram counts for the simulated PITs
        [sim_counts, ~] = histcounts(simulated_PIT, edges);

        % S statistic for the simulated data
        S_stat_sim(sim) = sum((sim_counts - expected_count).^2 / expected_count);
    end


end